import React, { useEffect } from 'react';
import { HashRouter, Routes, Route, Navigate, useNavigate } from 'react-router-dom';
import Login from './pages/public/login/Login';
import MainLayout from './layouts/main/MainLayout';
import EngineLayout from './layouts/engine/EngineLayout';
import './styles/index.css'
import { observer } from 'mobx-react-lite';
import { loginStore } from './store/public/loginStore';
import { eventBus, EVENT_TYPES } from './utils/eventBus';

// 创建一个内部组件来处理导航逻辑
const AppContent: React.FC = observer(() => {
  const navigate = useNavigate();

  useEffect(() => {
    // 订阅导航事件
    const handleNavigate = (path: string) => {
      navigate(path);
    };

    eventBus.on(EVENT_TYPES.NAVIGATE, handleNavigate);

    // 清理订阅
    return () => {
      eventBus.off(EVENT_TYPES.NAVIGATE, handleNavigate);
    };
  }, [navigate]);

  return (
    <Routes>
      <Route path="/" element={<Navigate to="/app" replace />} />
      <Route path="/login" element={<Login />} />
      <Route path="/app/*" element={loginStore.isAuthenticated ? <MainLayout /> : <Navigate to="/login" />} />
      <Route path="/engine/*" element={loginStore.isAuthenticated ? <EngineLayout /> : <Navigate to="/login" />} />
    </Routes>
  );
});

// 主 App 组件
const App: React.FC = () => {
  return (
    <HashRouter>
      <AppContent />
    </HashRouter>
  );
};

export default App;
